const express = require('express');
const app = express();
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const { getTBS2 } = require('./src/utils');
const { deleteReplies } = require('./src/deleteReply')
const { deletePosts } = require('./src/deletePost')
const { deleteConcerns } = require('./src/deleteConcern')
const { deleteTieba } = require('./src/deleteTieba')
const { deleteFans } = require('./src/deleteFans')

const port = 3000; // 可根据需要修改端口号

// 用于存储每个用户操作的状态等信息，以用户的WebSocket连接对象为键
let userOperationStatus = [];



// 创建WebSocket服务器
const wss = new WebSocket.Server({ noServer: true });

// 处理WebSocket连接
wss.on('connection', function connection(ws) {
    // 为每个新连接的用户初始化操作状态信息

    let config = {
        isRunning: false,
        cookie: null,
        reply: { enable: false, start: 1, end: 2 },
        post: { enable: false, start: 1, end: 2 },
        tieba: { enable: false, start: 1, end: 2 },
        concern: { enable: false, start: 1, end: 2 },
        fans: { enable: false, start: 1, end: 2 },
        tbs: '',
    };
    // userOperationStatus.push(ws);
    userOperationStatus.push({
        ws,
        config
    });
    ws.on('message', async function incoming(message) {
        console.log("开始啦....");

        try {
            const data = JSON.parse(message);
            if (data.type === 'start') {
                config.isRunning = "NO";
                config.cookie = data.cookie
                config.reply = data.reply
                config.post = data.post
                config.tieba = data.tieba
                config.concern = data.concern
                config.fans = data.fans
                const tbs = await getTBS2(data.cookie)
                config.tbs=tbs
                if (!tbs) {
                    ws.send(JSON.stringify({ status: 'stopped', message: 'cookie失效' }));
                } else {

                    try {
                        config.isRunning = "YES";
                        // 执行过程，这里假设你后续会完善具体的执行逻辑
                        ws.send(JSON.stringify({ status: 'completed', message: 'cookie有效,开始执行下一步' }));

                        if (config.reply.enable) {
                            ws.send(JSON.stringify({ status: 'start', message: `开始删除回贴` }));
                            await deleteReplies(config.reply,ws,config)
                        }
                        if (config.post.enable) {
                            ws.send(JSON.stringify({ status: 'start', message: `开始删除发帖` }));
                            await deletePosts(config.post)
                        }
                        if (config.tieba.enable) {
                            ws.send(JSON.stringify({ status: 'start', message: `开始取消关注贴吧` }));
                            await deleteTieba(config.tieba)
                        }
                        if (config.concern.enable) {
                            ws.send(JSON.stringify({ status: 'start', message: `开始清理关注` }));
                            await deleteConcerns(config.concern)
                        }
                        if (config.fans.enable) {
                            ws.send(JSON.stringify({ status: 'start', message: `开始清理粉丝` }));
                            await deleteFans(config.fans,ws,config)
                        }

                        ws.send(JSON.stringify({ status: 'completed', message: '所有操作已完成！' }));
                    } catch (error) {
                        config.isRunning = "NO";
                        ws.send(JSON.stringify({ status: 'error', message: `操作出错：${error}` }));
                    }
                }
            } else if (data.type === 'stop') {
                const index = userOperationStatus.indexOf(findClientByWs(ws));
                userOperationStatus[index].config.isRunning=false;
                ws.send(JSON.stringify({ status: 'stopped', message: '操作已停止' }));
            }
        } catch (error) {

            ws.send(JSON.stringify({ status: 'error', message: `解析消息出错：${error}` }));
        }
    });

    // 当WebSocket连接关闭时，清理对应的用户状态信息
    ws.on('close', function () {
        console.log("客户端断开..");
        const index = userOperationStatus.indexOf(findClientByWs(ws));
        console.log(userOperationStatus[index].config)
        if (index !== -1) {
            userOperationStatus.splice(index, 1);
        }
        // userOperationStatus = userOperationStatus.filter(userWs => userWs!== ws);
    });
    // 根据WebSocket实例查找对应的客户端信息
    function findClientByWs(ws) {
        return userOperationStatus.find(client =>
            client.ws === ws
        );
    }
});

// 处理根路径的GET请求，读取外部的.vue或.html文件并返回
app.get('/', function (req, res) {
    const filePath = path.join('public', 'index.html'); // 这里替换为实际的文件名，如index.html或main.vue等
    fs.readFile(filePath, 'utf8', function (err, data) {
        if (err) {
            res.status(500).send('读取页面文件出错');
        } else {
            res.send(data);
        }
    });
});

app.get('/status', function (req, res) {
    const clientCount = Object.keys(userOperationStatus).length;
    res.json({
        status: 200, // 这里设置表示成功的状态码，可以根据实际需求调整
        clientCount: clientCount
    });
});

// 将WebSocket服务器与Express服务器集成
const server = app.listen(port, function () {
    console.log(`Web服务器已启动，监听端口 ${port}`);
});

server.on('upgrade', function upgrade(request, socket, head) {
    wss.handleUpgrade(request, socket, head, function done(ws) {
        wss.emit('connection', ws);
    });
});